package edu.fpa.day0806;

import java.util.ArrayList;
import java.util.List;

public class SynCinema02 {
    public static void main(String[] args) {
        List<Integer> list1 = new ArrayList<Integer>();
        Cinema1 cinema = new Cinema1(list1,"影院");
        list1.add(1);
        list1.add(2);
        list1.add(4);
        list1.add(6);
        list1.add(3);
        list1.add(5);
        list1.add(8);
        List<Integer> list2 = new ArrayList<Integer>();
        list2.add(1);
        list2.add(2);
        list2.add(4);
        Customer1 customer1 = new Customer1(cinema,list2,"a");
        List<Integer> list3 = new ArrayList<Integer>();
        list3.add(3);
        list3.add(2);
        list3.add(4);
        Customer1 customer2 = new Customer1(cinema,list3,"b");
        List<Integer> list4 = new ArrayList<Integer>();
        list4.add(5);
        list4.add(6);
        list4.add(8);
        Customer1 customer3 = new Customer1(cinema,list4,"c");
        customer1.start();
        customer2.start();
        customer3.start();

    }
}
class Cinema1{
    List<Integer> available;
    String name;
    public Cinema1(List<Integer> available, String name) {
        super();
        this.available = available;
        this.name = name;
    }
    public boolean buyticket(List<Integer> seat) {
        System.out.println("可用位置为："+available.toString());

        List<Integer> copy = new ArrayList<Integer>();
        copy.addAll(available);
        copy.removeAll(seat);
        if(available.size()-copy.size()==seat.size()) {
            available=copy;
            return true;
        }else {
            return false;
        }
    }
}

class Customer1 extends Thread{

    Cinema1 cinema;
    List<Integer> seats;
    boolean flag;
    public Customer1(Cinema1 cinema, List<Integer> seats,String name) {
        super(name);
        this.cinema = cinema;
        this.seats = seats;
    }

    @Override
    public void run() {
        synchronized (cinema){
            flag = cinema.buyticket(seats);
            if(flag) {
                System.out.println(Thread.currentThread().getName()+"->购票成功"+seats.toString());
            }
            else {
                System.out.println(Thread.currentThread().getName()+"->购票失败");
            }
        }
    }

}